package concurrensy.producer_consumer;

import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffer.CircularFifoBuffer;

public class RingBufferWithSynchronized implements RingBuffer{

	private final Buffer buffer;

	public RingBufferWithSynchronized(int maxBufferSize) {
		buffer = new CircularFifoBuffer(maxBufferSize);
	}

	@Override
	public synchronized void addProduct(Object product) {
		final CircularFifoBuffer buffer = (CircularFifoBuffer)this.buffer;
		if (buffer.size() == buffer.maxSize()) {
			try {
				wait();
				System.out.println("Producer waitong for product picking");
				return;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			buffer.add(product);
			System.out.println("Producer add product");
			notifyAll();
		}	
	}

	@Override
	public synchronized void getProduct() {
		if (buffer.isEmpty()) {
			try {
				wait();
				System.out.println("Consumer waiting for product adding");
				return;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} else {
			buffer.remove();
			System.out.println("Consumer pick product");
			notifyAll();
		}
	}
}
